<template>
  <div>
    <div class="files c-shadow">
      <div class="files-upload">
         <ul class='clearFix'>
          <router-link class="nav-item" tag='li' to='/sysManage/filesUpload' active-class="selected">企业文件上传</router-link>
          <router-link class="nav-item" tag='li' to='/sysManage/listUpload' active-class="selected">企业文件列表</router-link>
        </ul>
        </div>
    </div>
    <!-- 文件上传 -->
    <div class="main-contant c-shadow">
      <h3>企业文件上传</h3>
      <div class="line"></div>
      <div class="upload-box">
        <el-form label-width="100px" :model="postData" :rules="rules" ref="postData">
          <el-form-item label="企业名称：" prop="entName" :disabled="edit">
            <!-- <el-input class="ent-name" placeholder="输入企业名称或者关键词" clearable v-model="postData.entName"></el-input> -->
            <el-autocomplete 
              style="width:100%"
              v-model="postData.entName" 
              :fetch-suggestions="querySearchAsync" 
              :trigger-on-focus="false" 
              @select="handleSelect"
              placeholder="请输入内容"
            >
            </el-autocomplete>
          </el-form-item>
          <el-form-item label="文件类型：" prop="fileType">
            <el-select v-model="postData.fileType" placeholder="请选择" class="ent-name menu-down" style="width:100%">
              <el-option v-for="item in items" :key="item.value" :label="item.label" :value="item.label">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上传说明：">
            <el-input class="ent-name" type="textarea" :rows="4" placeholder="" v-model="postData.uplodeDescribe"></el-input>
          </el-form-item>
          <el-form-item label="文件上传：" :error="fileError">
            <el-upload :action="uploadAction"
              :before-upload="beforeAvatarUpload"
              :limit="10"
              name="resFile"
              :data="fileName"
              :accept="acceptList"
              :on-success="uploadSuccess"
              :on-error="uploadError"
              :file-list="fileList"
              :on-remove="delFile">
              <el-button size="small" plain :disabled="uploadState">点击上传</el-button>
            </el-upload>
          </el-form-item>
          <p class="center">
            <span class="requir" v-if="requshow">没有此企业名称，请重新填写！</span>
          </p>
          <el-form-item>
            <el-button class="btn" type="primary" @click="upload">上 传</el-button>
            <el-button class="btn" type="primary" plain v-if="edit" @click="goHistory">取 消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
import { jDatePicker } from '../../components'
import { sysManage as api } from '../../api'
export default {
  components: { jDatePicker },
  data() {
    return {
      id: '',
      edit: false,
      uploadState: false,
      requshow: false,
      postData: {
        entName: '',
        fileType: null,
        uplodeDescribe: ''
      },
      param: '',
      fileList: [],
      uploadUrl: window.api_host + '/entDataUpload/addDataUpload',
      rules: {
        entName: [
          { required: true, message: '请输入关联的企业名称', trigger: 'blur' },
          { max: 50, message: '最多不能超过50个字符', trigger: 'blur' }
        ],
        fileType: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ]
      },
      items: [
        { value: 1, label: '财务报表' },
        { value: 2, label: '税务报表' },
        { value: 3, label: '水电报表' },
        { value: 4, label: '排查报表' },
        { value: 5, label: '其他' }
      ],
      uploadAction: window.api_upload,
      fileName: {
        filename: ''
      },
      acceptList: 'application/pdf,application/vnd.ms-excel,application/msword,application/vnd.ms-works,image/*,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      fileError: ''
    }
  },
  methods: {
    // 取消上传
    goHistory() {
      history.back()
    },
    // 输入检索
    querySearchAsync(queryString, callback) {
      let list = []
      let params = {entName: queryString}
      api.getentDataUpload(params).then(res => {
        for (let i = 0; i < res.data.length; i++) {
          list.push({'value': res.data[i]})
        }
        console.log(res)
        if (list && list.length > 0) {
          callback(list)
          this.requshow = false
        } else {
          this.requshow = true
          // this.$msgbox({
          //   title: '获取失败',
          //   message: '<span>获取已有数据失败</span>',
          //   center: true,
          //   roundButton: true,
          //   customClass: 'messageBox',
          //   type: 'info',
          //   dangerouslyUseHTMLString: true,
          //   callback: () => {}
          // })
          callback(list)
        }
      }).catch(res => {
        console.log(res.msg)
      })
    },
    handleSelect(item) {
      console.log('已经选择:' + item)
    },
    resetForm() {
      this.postData.entName = ''
      this.postData.fileType = '请选择'
      this.postData.uplodeDescribe = ''
      this.fileList = []
    },
    upload() {
      if (this.postData.fileType === '请选择') {
        this.postData.fileType = null
      }
      this.$refs['postData'].validate((valid) => {
        if (valid) {
          if (this.fileList.length === 0) {
            this.fileError = '请上传文件'
          } else {
            let params = this.postData
            params.resFile = JSON.stringify(this.fileList)
            if (this.edit) {
              api.postUpdateUpload(params).then(res => {
                if (res.code === -1) return false
                this.tips('上传成功', 'success').then(res => {
                  this.resetForm()
                })
              }).catch(res => {
                this.tips('错误:' + res.msg, 'error')
              })
            } else {
              let list = []
              api.getentDataUpload({entName:params.entName}).then(res => {
                for (let i = 0; i < res.data.length; i++) {
                  list.push({'value': res.data[i]})
                }
                if (list.length > 0) {
                  api.postDataUpload(params).then(res => {
                    this.tips('上传成功', 'success').then(res => {
                      this.requshow = false
                      this.resetForm()
                    })
                  }).catch(res => {
                    this.tips('错误:' + res.msg, 'error')
                  })
                } else {
                  // this.tips('错误:' + '本库没有该企业，请重新填写企业名称', 'error')
                  this.requshow = true
                }
              })
            }
          }
        } else {
          return false
        }
      })
    },
    beforeAvatarUpload(file) {
      // console.log(file.type)
      // console.log(file)
      if (file.type !== 'application/pdf' && file.type !== 'application/vnd.ms-excel' && file.type !== 'application/msword' && file.type !== 'application/vnd.ms-works' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' && file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
        // this.fileList.unshift({name: this.fileName.filename, url: ''})
        this.tips('请上传 pdf,doc,xls 文件', 'warning')
        return false
      }
      if (file.size > 31457280) {
        // this.fileList.unshift({name: this.fileName.filename, url: ''})
        this.tips('上传文件不得大于30M', 'warning')
        return false
      }
      if (file.size <= 0) {
        // this.fileList.unshift({name: this.fileName.filename, url: ''})
        this.tips('上传文件不得为空', 'warning')
        // console.log(this.fileList)
        return false
      }
      this.fileName.filename = file.name
      this.uploadState = true
      this.fileError = ''
      let fd = new FormData()
      fd.append('file', file)
      // console.log(fd)
      api.uploadAction(fd).then(res => {
        console.log(res)
      }, res => {
        console.log(res)
      })
    },
    uploadSuccess(res, file, List) {
      let that = this
      if (res.code === 1) {
        let respone = res.data
        for (var i = 0; i < respone.length; i++) {
          that.fileList.push({name: that.fileName.filename, url: respone[i].resOriginalUrl})
        }
      } else {
        this.tips(res.msg, 'warning')
      }
      this.uploadState = false
    },
    uploadError() {
      this.tips('上传失败：' + '系统错误', 'error')
      this.uploadState = false
    },
    delFile(file, list) {
      // this.fileList.splice(list, 1)
      if (list.length === 0) {
        this.fileList = []
      } else {
        this.fileList = []
        list.map(item => {
          this.fileList.push({name: item.name, url: item.url})
        })
      }
    }
  },
  mounted() {
    let id = this.$route.query.id
    let edit = this.$route.query.edit
    this.id = id
    this.edit = edit
    if (edit) {
      let params = {id: id}
      api.postSelectDetail(params).then(res => {
        this.postData = res.data
      }).catch(res => {
        this.tips(res.msg, 'error')
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.files-upload {
  padding-left: 20px;
  display: flex;
  .selected {
    background: #e8f1fa;
    border-bottom: 3px solid #1470cc;
    color: #1470cc;
  }
  ul {
    width: 100%;
    li {
      float: left;
      height: 52px;
      text-align: center;
      line-height: 52px;
      font-size: 16px;
      cursor: pointer;
      white-space: normal;
      width: 15%;
      border-bottom: 3px solid transparent;
      &:hover {
        background: #e8f1fa;
        border-bottom: 3px solid #1470cc;
        color: #1470cc;
      }
    }
  }
}
.main-contant {
  margin-top: 20px;
  padding: 20px 20px;
  min-height: 470px;
  h3 {
    width: 100%;
    padding-left: 10px;
    height: 17px;
    line-height: 17px;
    border-left: 4px solid #1890ef;
    font-size: 16px;
    font-weight: bold;
  }
  .line {
    width: 98%;
    margin-top: 13px;
    border-bottom: 1px solid #ccc;
  }
  .center {
    .requir {
      margin: 5px 0 15px 50px;
      display: inline-block;
      color: red;
    }
  }
  .upload-box{
    padding-top: 60px;
    width:550px;
    margin:auto
  }
  .upload-details {
    display:none;
    margin-top: 60px;
    text-align: center;
    .upload-matter {
      margin-top: 25px;
    }
    .upload-matter:nth-child(1) {
      margin-top: 0px;
    }
    label {
      color: #999;
      font-size: 14px;
      span {
        color: red;
        margin-right: 5px;
      }
    }
    .ent-name {
      width: 457px;
      height: 36px;
      line-height: 36px;
      vertical-align: middle;
      background-color: #ffffff;
      border-radius: 5px;
    }
    .select-name {
      display: block;
      margin-top: 10px;
      color: #999;
      margin-right: 22%;
    }
    .menu-down {
      i {
        line-height: 36px;
      }
    }
    .menu-explain {
      height: 107px;
      vertical-align: top;
      .explain {
        margin-right: 11px;
      }
    }
    .upload-accessory {
      display: flex;
      margin-left: 28%;
      .accessory {
        margin-left: 10px;
      }
      .sc {
        color: #3197ff;
        font-size: 14px;
        i {
          font-size: 16px;
          margin-right: 5px;
        }
      }
    }
    .btn {
      width: 111px;
      height: 34px;
      line-height: 4px;
      margin-top: 30px;
    }
  }
}
</style>




// WEBPACK FOOTER //
// src/view/sysManage/filesUpload.vue